package com.baomidou.springboot.spark;

import com.baomidou.springboot.constant.Constants;
import com.baomidou.springboot.utils.StringUtils;
import org.apache.spark.AccumulatorParam;

/**
 * Created by pcmmm on 17/6/15.
 */
public class TimeAccumulator implements AccumulatorParam<String> {
    @Override
    public String zero(String v) {
        return Constants.TIME_0_1 + "=0|"
                + Constants.TIME_1_2 + "=0|"
                + Constants.TIME_2_3 + "=0|"
                + Constants.TIME_3_4 + "=0|"
                + Constants.TIME_4_5 + "=0|"
                + Constants.TIME_5_6 + "=0|"
                + Constants.TIME_6_7 + "=0|"
                + Constants.TIME_7_8 + "=0|"
                + Constants.TIME_8_9 + "=0|"
                + Constants.TIME_9_10 + "=0|"
                + Constants.TIME_10_11 + "=0|"
                + Constants.TIME_11_12 + "=0|"
                + Constants.TIME_12_13 + "=0|"
                + Constants.TIME_13_14 + "=0|"
                + Constants.TIME_14_15 + "=0|"
                + Constants.TIME_15_16 + "=0|"
                + Constants.TIME_16_17 + "=0|"
                + Constants.TIME_17_18 + "=0|"
                + Constants.TIME_18_19 + "=0|"
                + Constants.TIME_19_20 + "=0|"
                + Constants.TIME_20_21 + "=0|"
                + Constants.TIME_21_22 + "=0|"
                + Constants.TIME_22_23 + "=0|"
                + Constants.TIME_23_0 + "=0|";
    }
    @Override
    public String addInPlace(String v1, String v2) {
        return add(v1, v2);
    }

    @Override
    public String addAccumulator(String v1, String v2) {
        return add(v1, v2);
    }

    private String add(String v1, String v2) {
        // 校验：v1为空的话，直接返回v2
        if(StringUtils.isEmpty(v1)) {
            return v2;
        }

        // 使用StringUtils工具类，从v1中，提取v2对应的值，并累加1
        String oldValue = StringUtils.getFieldFromConcatString(v1, "\\|", v2);
        if(oldValue != null) {
            // 将范围区间原有的值，累加1
            int newValue = Integer.valueOf(oldValue) + 1;
            // 使用StringUtils工具类，将v1中，v2对应的值，设置成新的累加后的值
            return StringUtils.setFieldInConcatString(v1, "\\|", v2, String.valueOf(newValue));
        }

        return v1;
    }
}
